#!/usr/bin/env bash

# set on caller scripts
values=${values:-1}

[ "${tests[*]}" ] || echo 'Array $tests undefined, I need it.'

# You can force a global debug here
# debug=1

# now the fun begins
zz=../funcoeszz
[ "$color" != 1 ] && export ZZCOR=0 || export ZZCOR=1
num_tests=${#tests[*]}
i=-1

while [ $i -lt $((num_tests-1)) ]; do
	# collect v1 to v6
	[ $values -ge 1 ] && i=$((i+1)) && v1="${tests[$i]}"
	[ $values -ge 2 ] && i=$((i+1)) && v2="${tests[$i]}"
	[ $values -ge 3 ] && i=$((i+1)) && v3="${tests[$i]}"
	[ $values -ge 4 ] && i=$((i+1)) && v4="${tests[$i]}"
	[ $values -ge 5 ] && i=$((i+1)) && v5="${tests[$i]}"
	[ $values -ge 6 ] && i=$((i+1)) && v6="${tests[$i]}"

	# collect correct results
	i=$((i+1)) ; mode="${tests[$i]}"
	i=$((i+1)) ; ok=$(echo -e "${tests[$i]}")
	
	[ "$debug" = 1 ] && echo "+ ${0##*/} $v1 $v2 $v3 $v4 $v5 $v6"

	# execute tests
	case $values in
		0) result=$("$zz" ${0##*/}) ;;
		1) result=$("$zz" ${0##*/} $v1) ;;
		2) result=$("$zz" ${0##*/} $v1 $v2) ;;
		3) result=$("$zz" ${0##*/} $v1 $v2 $v3) ;;
		4) result=$("$zz" ${0##*/} $v1 $v2 $v3 $v4) ;;
		5) result=$("$zz" ${0##*/} $v1 $v2 $v3 $v4 $v5) ;;
		6) result=$("$zz" ${0##*/} $v1 $v2 $v3 $v4 $v5 $v6) ;;
	esac
	
	# test results against OK data
	error=
	case "$mode" in
		t) [ "$result" = "$ok" ] || error=1
		;;
		r) echo "$result" | egrep -qs "$ok" || error=1
		;;
		a) echo "$result" > _out ; diff "$ok" _out || error=1
		;;
		#
		# ISO-8859-1:
		# a) echo "$result" > _out
		#    iconv -f utf-8 -t iso-8859-1 $ok > $ok.iso
		#    diff "$ok.iso" _out || error=1
		# ;;
		*) echo Invalid mode: $mode
		;;
	esac
	[ "$error" ] || continue
	
	# summarize output
	ok=$(echo -n "$ok" | tr '\n' ' ' | cut -c1-30)
	result=$(echo -n "$result" | tr '\n' ' ' | cut -c1-30)
	
	echo "ERROR: ${0##*/} $v1 $v2 $v3 $v4 $v5"
	echo "expected '$ok', got '$result'"
done

rm -f _tmp* _out
